import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_09_game/application.dart';
import 'package:flutter_09_game/base/refresh/base_refresh.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/config/app_routes.dart';
import 'package:flutter_09_game/config/app_theme.dart';
import 'package:flutter_09_game/config/history_route_ovserver.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/manager/ws_manager.dart';
import 'package:flutter_09_game/pages/main/main_logic.dart';
import 'package:flutter_09_game/user/model/model_user_wallet.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/widgets/button/common_button.dart';
import 'package:flutter_09_game/widgets/dialog/common_normal_sheet.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'package:flutter_09_game/user/model/app_user_info_model.dart';

import 'package:flutter_09_game/utils/shared/shared_key.dart';
import 'package:flutter_09_game/utils/shared/shared_storage.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../http/http_export.dart';

/// 记录登录后用户信息
///
class AppUserManager {
  static final AppUserManager _instance = AppUserManager._();

  factory AppUserManager() => _instance;

  AppUserManager._() {
    // // 超过30天需要重新登录
    // int? loginTime = SharedStorage().prefs.getInt(SharedKey.loginTime);
    // if (loginTime != null) {
    //   int time = DateTime.now()
    //       .subtract(const Duration(days: 30))
    //       .millisecondsSinceEpoch;
    //   if (time > loginTime) {
    //     return;
    //   }
    // }

    token = SharedStorage().prefs.getString(SharedKey.token) ?? "";
    String? info = SharedStorage().prefs.getString(SharedKey.userInfo);
    if (info != null) {
      user.value =
          AppUserInfoModelUser.fromJson(json.decode(info.toBase64Decode));
      // refreshUserInfo();
      // loadWalletData();
    }
  }

  Rxn<AppUserInfoModelUser> user = Rxn();

  Rxn<AppUserInfoModelTeam> teamRx = Rxn();

  RxList<ModelUserWallet> walletList = RxList();
  Rx<ModelUserWallet> currentWalletRx = ModelUserWallet().obs;

  String token = "";

  int? get uid => user.value?.id;

  void remove() {
    token = "";
    user.value = null;

    SharedStorage().prefs.remove(SharedKey.token);
    SharedStorage().prefs.remove(SharedKey.userInfo);
  }

  bool isLogin() => token.isNotEmpty;

  Future refreshUserInfo({bool showLoad = false}) async {
    var res = await HttpManager().get(API.getUserProfile,
        fromJson: AppUserInfoModel.fromJson,
        uiType: showLoad ? HttpUIType.loadingAndToast : HttpUIType.toast);
    if (res.isSuccess) {
      updateUserInfo(res.data.user);
      updateUserTeam(res.data.team);
    }
    return res.isSuccess;
  }

  // getUserInfoStats

  //0退出即可，1异地登录，登录过期，2账号禁用
  Future<void> logout({int type = 0}) async {
    if (token.isEmpty) {
      return;
    }
    if (Get.isRegistered<MainLogic>()) {
      Get.find<MainLogic>().changeIndex(0);
    }
    // 断开WebSocket连接
    WsManager().disconnect();
    remove();
    token = "";
    user.value = null;
    walletList.value = [];
    currentWalletRx.value = ModelUserWallet();

    // 跳转到主页并选择首页
    // 直接跳转到主页，确保无论当前在哪个页面都能回到首页
    // Get.offAllNamed(AppRoutes.splash);

    Get.until((routing) => routing.settings.name == AppRoutes.main);
  }

  Future updateUserInfo(
    AppUserInfoModelUser userInfo,
  ) async {
    user.value = userInfo;

    await SharedStorage()
        .prefs
        .setString(SharedKey.userInfo, json.encode(userInfo).toBase64Encode);
  }

  Future updateUserTeam(
    AppUserInfoModelTeam team,
  ) async {
    teamRx.value = team;
  }

  Future<bool> updateToken(String? t) async {
    // if (t != null && token != t) {
    token = t ?? "";

    // 如果token不为空，连接WebSocket
    // if (token.isNotEmpty) {
    //   WsManager().connectWithToken(token);
    // }

    return await SharedStorage().prefs.setString(SharedKey.token, t ?? '');
  }

  /// 判断传入的 userId 是否和当前用户 id 相同
  static bool isSameUser(int? userId) {
    final currentUserId = AppUserManager().user.value?.id;
    return userId != null && currentUserId != null && userId == currentUserId;
  }

  // 更新用户信息
  static Future<HttpResponse> updateUserInfoToServer({
    String? username,
    String? avatar,
    // String? bio,
    bool showLoading = true,
  }) async {
    var params = <String, dynamic>{};
    if (username != null) {
      params['username'] = username;
    }
    if (avatar != null) {
      params['avatar'] = avatar;
    }

    HttpResponse response = await HttpManager().put(API.putUserProfile,
        params: params,
        uiType: showLoading ? HttpUIType.loadingAndToast : HttpUIType.none);

    // 如果服务器更新成功且需要同步到IM，则更新IM用户信息
    if (response.isSuccess) {
      AppUserInfoModelUser user = AppUserInfoModelUser.fromJson(response.data);

      AppUserManager().updateUserInfo(user);
    }
    return response;
  }

  /// 加载钱包数据
  Future<void> loadWalletData({bool showLoad = false}) async {
    final startTime = DateTime.now();
    HttpResponse response = await HttpManager().get(
      API.getWallet,
      fromJson: ModelUserWallet.fromJson,
      uiType:
          showLoad ? HttpUIType.loading : HttpUIType.none, // 静默加载，不显示loading
    );
    final endTime = DateTime.now();
    clog(
        '请求API.getWallet耗时: ${endTime.difference(startTime).inMilliseconds} ms');

    if (response.isSuccess) {
      walletList.value = response.data;

      if (walletList.isNotEmpty && currentWalletRx.value.symbol == null) {
        currentWalletRx.value = walletList.first;
      } else {
        ModelUserWallet? wallet = walletList.firstWhereOrNull(
            (item) => item.symbol == currentWalletRx.value.symbol);
        if (wallet?.balance != currentWalletRx.value.balance) {
          clog('daskdjlkasd ${wallet?.balance}');
        }

        if (wallet != null) {
          currentWalletRx.value = wallet;
        }
      }

      // prizePoolRx.value = response.data;
    }
  }

  selectUserWallet(String symbol) {
    ModelUserWallet? wallet =
        walletList.firstWhereOrNull((item) => item.symbol == symbol);
    if (wallet != null) {
      currentWalletRx.value = wallet;
    }
  }

  showServiceSheet() {
    CommonNormalSheet(
        title: LocaleKeys.contactService.tr,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              AutoImage(
                Assets.mineServiceBg,
                width: 343.w,
                height: 100.w,
                fit: BoxFit.fitWidth,
              ),
              24.verticalSpaceFromWidth,
              Container(
                padding: EdgeInsets.all(12.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.w),
                  color: Colors.black.withOpacity(0.3),
                  border: Border(
                      bottom: BorderSide(
                          color: AppColor.textPrimary.withOpacity(0.15),
                          width: 1)),
                ),
                child: Row(
                  children: [
                    AutoImage(
                      Assets.mineServiceBtnTag,
                      width: 44.w,
                    ),
                    8.horizontalSpace,
                    Expanded(
                        child: Text(
                      LocaleKeys.onlineService.tr,
                      style: TextStyle(
                          color: AppColor.textPrimary.withOpacity(0.94),
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500),
                    )),
                    12.horizontalSpace,
                    CommonButton(
                      // width: 68.w,
                      height: 32.w,
                      title: LocaleKeys.clickToJump.tr,
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w600,
                      backgroundColors: [
                        AppColor.primary.withOpacity(0.3),
                        AppColor.primary.withOpacity(0.3),
                      ],

                      onClick: () {
                        String? url = AppConfig.getServiceUrl();
                        if (url != null) {
                          // Get.back();
                          routeHistoryObserver
                              .removeName(CommonNormalSheet.name);
                          Get.toNamed(AppRoutes.webServicePage,
                              arguments: {'url': url});
                          // launchUrlString(url,
                          //     mode: LaunchMode.externalApplication);
                        }
                      },
                    ),
                  ],
                ),
              ),
              24.verticalSpaceFromWidth,
            ],
          ),
        )).show();
  }
}
